package com.th.common.utils.pdf;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.th.common.config.NswcyConfig;
import com.th.common.exception.GlobalException;
import com.th.common.utils.DateUtils;
import com.th.common.utils.base64.picture.BASE64DecodedMultipartFile;
import com.th.common.utils.file.FileUtils;
import io.jsonwebtoken.lang.Collections;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Pdf工具类
 *
 * @author: tuhang
 * @date: 2022/5/13
 **/
public class PdfUtils {

    /**
     * 插入base64图片到PdfStamper对象中
     *
     * @param fieldName   表当名
     * @param imageBase64 base64格式图片
     */
    public static void insertPicToPdfStamper(PdfStamper stamper, AcroFields form, String fieldName, String imageBase64) throws DocumentException, IOException {
        List<AcroFields.FieldPosition> fieldPositions = form.getFieldPositions(fieldName);
        if (Collections.isEmpty(fieldPositions)) {
            throw new GlobalException("文件模板没有相应签名域");
        }

        int pageNo = form.getFieldPositions(fieldName).get(0).page;
        Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
        float x = signRect.getLeft();
        float y = signRect.getBottom();

        // 图片临时文件位置
        String tmpImagePath = NswcyConfig.getProfile() + "/tmp/" + UUID.randomUUID() + ".png";
        if (!FileUtils.mkdirDirIgnoreFile(tmpImagePath)) {
            throw new RuntimeException("临时文件夹创建失败");
        }

        // 存储base64图片为文件图片
        MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(imageBase64);
        assert multipartFile != null;
        multipartFile.transferTo(new File(tmpImagePath));

        // 读图片
        Image image = Image.getInstance(tmpImagePath);

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent(pageNo);

        // 根据域的大小缩放图片
        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
        // 添加图片
        image.setAbsolutePosition(x, y);

        under.addImage(image);
    }

    /**
     * 插入日期到指定域中
     *
     * @param y 年的表单名
     * @param m 月的表单名
     * @param d 日的表单名
     */
    public static void insertDateToForm(AcroFields form, String y, String m, String d) throws DocumentException, IOException {
        Date now = new Date();
        insertTextToForm(form, y, DateUtils.parseDateToStr("yyyy", now));
        insertTextToForm(form, m, DateUtils.parseDateToStr("yyyy", now));
        insertTextToForm(form, d, DateUtils.parseDateToStr("yyyy", now));
    }

    /**
     * 插入文本到指定域中
     *
     * @param fieldName 表单名
     * @param text      文本
     */
    public static void insertTextToForm(AcroFields form, String fieldName, String text) throws DocumentException, IOException {
        form.setField(fieldName, text, true);
    }

    /**
     * 判断是否存在相应的文本域
     * @param path pdf绝对文件路径
     * @param fieldName 表达名
     */
    public static boolean isFieldExist(String absolutePath, String fieldName) {
        PdfReader reader = null;
        try {
            reader = new PdfReader(new FileInputStream(absolutePath));
            AcroFields form = reader.getAcroFields();
            AcroFields.Item item = form.getFieldItem(fieldName);
            return item != null;
        } catch (IOException e) {
            if (reader != null) {
                reader.close();
            }
            e.printStackTrace();
        }

        return false;
    }
}
